<template>
  <div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        class="info-list"
      >
        <van-cell center title="添加新内容" icon="plus" @click="addData"/>
        <van-swipe-cell v-for="(item,index) in list" :key="index" stop-propagation :before-close="beforeClose" :name="index">
          <van-cell @click="editData(index)">
            <van-row type="flex" justify="space-between">
              <van-col span="16">
                <p style="font-size: 16px;font-weight: bold">{{item.title}}</p>
                <p style="font-size: 12px;color: #999">类型：{{item.imgList.length==1?"单图":"三图"}}</p>
              </van-col>
            </van-row>
          </van-cell>
          <van-button
            slot="right"
            square
            text="删除"
            type="danger"
            class="delete-button"
          />
        </van-swipe-cell>

      </van-list>
    </van-pull-refresh>
    <!--添加弹窗-->
    <van-popup
      style="padding:.5rem;border-radius: 12px"
      v-model="addShow"
      position="center"
    >

      <van-row type="flex" justify="space-between">
        <van-col span="24">
          <!-- 输入任意文本 -->
          <van-cell-group>
            <van-field v-model="form.title" label="标题" placeholder="标题"/>
            <van-field disabled @click="pickerShow=true" v-model="type" label="类型" placeholder="请选择类型"/>

            <div v-if="type=='三图'">
              <van-uploader :after-read="onUploadImg" :accept="'image/*'">
                <van-field v-model="form.imgList[0]" label="图片1" placeholder="请上传图片1"/>
              </van-uploader>
              <van-uploader :after-read="onUploadImg1" :accept="'image/*'">
                <van-field v-model="form.imgList[1]" label="图片2" placeholder="请上传图片2"/>
              </van-uploader>
              <van-uploader :after-read="onUploadImg2" :accept="'image/*'">
                <van-field v-model="form.imgList[2]" label="图片3" placeholder="请上传图片3"/>
              </van-uploader>

            </div>
            <div v-if="type=='单图'">
              <van-uploader :after-read="onUploadImg" :accept="'image/*'">
                <van-field v-model="form.imgList[0]" label="图片1" placeholder="请输入图片1链接"/>
              </van-uploader>
            </div>
            <van-field v-model="form.src" label="跳转链接" placeholder="请输入跳转链接"/>
          </van-cell-group>
        </van-col>

      </van-row>
      <!-- 两端对齐 -->
      <van-row type="flex" justify="space-between">
        <van-col span="24">
          <van-button block @click="addShow=false">取消</van-button>
        </van-col>
        <van-col span="24">
          <van-button block @click="addDataConfirm">确定</van-button>
        </van-col>
      </van-row>
    </van-popup>
    <!--编辑弹窗-->
    <van-popup
      style="padding:.5rem;border-radius: 12px"
      v-model="editShow"
      position="center"
    >

      <van-row type="flex" justify="space-between">
        <van-col span="24">
          <!-- 输入任意文本 -->
          <van-cell-group>
            <van-field v-model="form.title" label="标题" placeholder="标题"/>
            <van-field disabled @click="pickerShow=true" v-model="type" label="类型" placeholder="请选择类型"/>

            <div v-if="type=='三图'">
              <van-uploader :after-read="onUploadImg" :accept="'image/*'">
                <van-field v-model="form.imgList[0]" label="图片1" placeholder="请上传图片1"/>
              </van-uploader>
              <van-uploader :after-read="onUploadImg1" :accept="'image/*'">
                <van-field v-model="form.imgList[1]" label="图片2" placeholder="请上传图片2"/>
              </van-uploader>
              <van-uploader :after-read="onUploadImg2" :accept="'image/*'">
                <van-field v-model="form.imgList[2]" label="图片3" placeholder="请上传图片3"/>
              </van-uploader>

            </div>
            <div v-if="type=='单图'">
              <van-uploader :after-read="onUploadImg" :accept="'image/*'">
                <van-field v-model="form.imgList[0]" label="图片1" placeholder="请输入图片1链接"/>
              </van-uploader>
            </div>
            <van-field v-model="form.src" label="跳转链接" placeholder="请输入跳转链接"/>
          </van-cell-group>
        </van-col>

      </van-row>
      <!-- 两端对齐 -->
      <van-row type="flex" justify="space-between">
        <van-col span="24">
          <van-button block @click="editShow=false">取消</van-button>
        </van-col>
        <van-col span="24">
          <van-button block @click="editDataConfirm">确定</van-button>
        </van-col>
      </van-row>
    </van-popup>
    <van-popup
      v-model="pickerShow"
      position="bottom"

    >
      <van-picker :columns="columns" @change="onChange"/>
    </van-popup>
  </div>
</template>

<script>
  import {Notify,Dialog} from 'vant';

  export default {
    name: "Advert",
    data() {
      return {
        list: [],
        page: 0,
        form: {
          imgList: []
        },
        type: '单图',
        pickerShow: false,
        addShow: false,
        editShow: false,
        loading: false,
        finished: false,
        refreshing: false,
        columns: ["单图", '三图']
      }
    },
    methods: {
      beforeClose({name,position, instance}) {
        let id=this.list[name].id;
        switch (position) {
          case 'left':
          case 'cell':
          case 'outside':
            instance.close();
            break;
          case 'right':
            Dialog.confirm({
              message: '确定删除吗？'
            }).then((res) => {
              console.log(res)
              this.$post("/advert/del", {ids: [id]}).then(res => {
                if (res.code == 1) {
                  Notify({type: 'danger', message: '删除失败' + res.msg});
                  return;
                }
                Notify({type: 'success', message: '删除成功'});
                this.onRefresh();
              }).catch(function (err) {
                console.log(err);
              });
              instance.close();
            }).catch((res)=>{
              instance.close();
            });
            break;
        }

      },
      onChange(picker, value, index) {
        this.type = value;
        this.pickerShow = false;
      },
      onUploadImg(file) { // 上传图片到图片服务器
        let fd = new FormData()
        fd.append('file', file.file)
        Notify({type: 'warning', message: '上传中...'});
        this.$post('/admin/upload', fd, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.code == 0) {
            this.$set(this.form.imgList, 0, res.data.url)
            // this.form.imgList[0] = res.data.url //这里上传到指定的图片服务器，成功后会返回图片的url
            Notify({type: 'success', message: '上传成功'});
          } else {
            Notify({type: 'danger', message: '上传失败' + res.msg});
          }

        }).catch(err => {
          alert(err)
        })
      },
      onUploadImg1(file) { // 上传图片到图片服务器
        let fd = new FormData()
        fd.append('file', file.file)
        Notify({type: 'warning', message: '上传中...'});
        this.$post('/admin/upload', fd, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.code == 0) {
            this.$set(this.form.imgList, 1, res.data.url)
            // this.form.imgList[1] = res.data.url //这里上传到指定的图片服务器，成功后会返回图片的url
            Notify({type: 'success', message: '上传成功'});
          } else {
            Notify({type: 'danger', message: '上传失败' + res.msg});
          }

        }).catch(err => {
          alert(err)
        })
      },
      onUploadImg2(file) { // 上传图片到图片服务器
        let fd = new FormData()
        fd.append('file', file.file)
        Notify({type: 'warning', message: '上传中...'});
        this.$post('/admin/upload', fd, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.code == 0) {
            this.$set(this.form.imgList, 2, res.data.url)
            //this.form.imgList[2] = res.data.url //这里上传到指定的图片服务器，成功后会返回图片的url
            Notify({type: 'success', message: '上传成功'});
          } else {
            Notify({type: 'danger', message: '上传失败' + res.msg});
          }
        }).catch(err => {
          alert(err)
        })
      },
      onRefresh() {
        this.list = []
        this.page = 0;
        // 清空列表数据
        this.finished = false;
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        this.loading = true;
        this.onLoad();
      },
      onLoad() {
        this.getData()
      },
      getData() {
        if (this.refreshing) {
          this.list = [];
          this.refreshing = false;
        }
        this.page++
        this.loading = true;
        this.$get("/advert/list", {page: this.page}).then(res => {
          if (res.code == 1) {
            this.loading = false;
            this.finished = true;
            return;
          }

          this.loading = false;
          res.data.forEach((item) => {
            this.list.push(item);
          });

        }).catch(function (err) {
          console.log(err);
        });
      },
      addData() {
        this.form = {
          imgList: []
        }
        this.addShow = true;
      },
      addDataConfirm() {
        if (this.form.title == "" || this.form.title == undefined) {
          Notify({type: 'danger', message: '请输入标题'});
          return;
        }
        if (this.form.imgList.length == 0 || (this.form.imgList.length != 1 && this.imgList.imgList != 3)) {
          Notify({type: 'danger', message: '请输入上传广告图片'});
          return;
        }
        if (this.type == '单图') {
          if (this.form.imgList.length != 1) {
            Notify({type: 'danger', message: '请输入上传一张广告图片'});
            return;
          }

        } else {
          if (this.form.imgList.length != 3) {
            Notify({type: 'danger', message: '请输入上传三张广告图片'});
            return;
          }
        }
        if (this.form.src == "" || this.form.src == undefined) {
          Notify({type: 'danger', message: '请输入跳转地址'});
          return;
        }

        this.$post("/advert/add", this.form).then(res => {
          if (res.code == 1) {
            Notify({type: 'danger', message: '添加失败，' + res.msg});
            return;
          }
          Notify({type: 'success', message: '添加成功'});
          this.onRefresh();
          this.addShow = false;
        })
      },
      editData(index) {
        this.editShow = true;

        this.form = this.list[index];
        this.type = this.form.imgList.length == 1 ? "单图" : "三图";
        console.log(this.form);
      },
      editDataConfirm() {
        if (this.form.title == "" || this.form.title == undefined) {
          Notify({type: 'danger', message: '请输入标题'});
          return;
        }
        if (this.form.imgList.length == 0 || (this.form.imgList.length != 1 && this.imgList.imgList != 3)) {
          Notify({type: 'danger', message: '请输入上传广告图片'});
          return;
        }
        if (this.type == '单图') {
          if (this.form.imgList.length != 1) {
            Notify({type: 'danger', message: '请输入上传一张广告图片'});
            return;
          }

        } else {
          if (this.form.imgList.length != 3) {
            Notify({type: 'danger', message: '请输入上传三张广告图片'});
            return;
          }
        }
        if (this.form.src == "" || this.form.src == undefined) {
          Notify({type: 'danger', message: '请输入跳转地址'});
          return;
        }

        this.$post("/advert/update", this.form).then(res => {
          if (res.code == 1) {
            Notify({type: 'danger', message: '修改失败，' + res.msg});
            return;
          }
          Notify({type: 'success', message: '修改成功'});
          this.onRefresh();
          this.editShow = false;
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
  .time-line-right {
    position: relative;
    flex-grow: 1;
    margin-bottom: .72rem;
    padding: 20px 0;
    background: #fff;
    border-radius: .24rem;
    .right-title {
      font-weight: 600;
      font-size: 1rem;
      line-height: 1rem;
      text-overflow: ellipsis;
      i {
        display: inline-block;
        width: 2rem;
        height: 1rem;
        margin-right: .36rem;
        color: #fff;
        font-size: .72rem;
        font-style: normal;
        line-height: 1rem;
        text-align: center;
        background-color: #f74c31;
        border-radius: .12rem;
      }
    }
    .right-content {
      display: -webkit-box;
      margin-top: .04rem;
      overflow: hidden;
      color: #999;
      font-size: .72rem;
      line-height: 1rem;
      text-overflow: ellipsis;
      -webkit-line-clamp: 5;
    }
    .left-go {

      display: inline-block;
      left: .16rem;
      bottom: .12rem;
      margin-top: .08rem;
      color: #3243f7;
      font-size: .12rem;
      text-align: left;
    }
    .right-form {
      position: absolute;
      display: inline-block;
      right: .16rem;
      bottom: .12rem;
      margin-top: .04rem;
      color: #999;
      font-size: .12rem;
      text-align: right;
    }

  }

  .title {
    display: -webkit-box;
    margin-top: .04rem;
    overflow: hidden;
    color: #999;
    font-size: .72rem;
    line-height: 1rem;
    text-overflow: ellipsis;
    -webkit-line-clamp: 5;
  }

  .delete-button {
    height: 100%;
  }
</style>
